/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.finance.ap.memo.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.finance.ap.invoice.dao.model.ApInvoiceLine;
import com.erp.finance.ap.invoice.service.ApInvoiceLineService;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoLine;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoLineBase;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoLineCO;
import com.erp.finance.ap.memo.service.ApInvoiceMemoLineService;
import com.erp.finance.apeco.memo.dao.model.ApInvoiceMemoLineM;
import com.erp.finance.apeco.memo.service.ApInvoiceMemoLineMService;
import com.erp.inv.input.service.InvInputLineService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.po.dao.model.PoLine;
import com.erp.order.po.service.PoLineService;

@Controller
@RequestMapping("/web/apInvoiceMemoLine")
public class ApInvoiceMemoLineWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ApInvoiceMemoLineWebController.class);
    
    //服务层注入
    @Autowired
    private ApInvoiceMemoLineService apInvoiceMemoLineService;
    @Autowired
    private ApInvoiceLineService apInvoiceLineService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private PoLineService poLineService;
    @Autowired
    private InvInputLineService invInputLineService;
    @Autowired
    private ApInvoiceMemoLineMService apInvoiceMemoLineMService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getApInvoiceMemoLineList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-10-27 14:35:50
     * @author 
     * @param pages
     * @param apInvoiceMemoLineCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getApInvoiceMemoLineList")
    public String getApInvoiceMemoLineList(Pages pages, ApInvoiceMemoLineCO apInvoiceMemoLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //分页查询数据
        List<ApInvoiceMemoLineBase> lineList = new ArrayList<ApInvoiceMemoLineBase>();
        //根据version请求参数，判断数据从原表获取还是变更表获取
        if(apInvoiceMemoLineCO.getVersion()!=null&&apInvoiceMemoLineCO.getVersion()>0) {
            ApInvoiceMemoLineM apInvoiceMemoLineM = new ApInvoiceMemoLineM();
            apInvoiceMemoLineM.setInvoiceHeadCode(apInvoiceMemoLineCO.getInvoiceHeadCode());
            apInvoiceMemoLineM.setVersion(apInvoiceMemoLineCO.getVersion());
            List<ApInvoiceMemoLineM> list = this.apInvoiceMemoLineMService.getDataObjects(pages, apInvoiceMemoLineM);
            for(ApInvoiceMemoLineM obj: list) {
                lineList.add(obj);
            }
        }else {
            List<ApInvoiceMemoLine> list = this.apInvoiceMemoLineService.getApInvoiceMemoLineListByHeadCode(pages, apInvoiceMemoLineCO);
            for(ApInvoiceMemoLine obj: list) {
                lineList.add(obj);
            }
        }
        
        for(ApInvoiceMemoLineBase line: lineList) {
            //获取发票信息
            ApInvoiceLine apInvoiceLine = this.apInvoiceLineService.getDataObject(line.getInvoiceSourceLineCode());
            
            PoLine poLine = this.poLineService.getDataObject(apInvoiceLine.getInvoiceSourceLineCode());
            line.setMaterialCode(poLine.getMaterialCode());
            line.setMaterialName(materialMap.get(poLine.getMaterialCode()).toString());
            line.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(poLine.getMaterialCode()).getStandard());
            line.setPrice(poLine.getPrice());
            line.setUnit(materialUnitMap.get(poLine.getUnit()).toString());
            line.setPoLineAmount(apInvoiceLine.getAmount());
        }
        
        //页面属性设置
        model.addAttribute("payLineList", lineList);
        model.addAttribute("pages", pages);
        
        return "apInvoiceMemo/tab/apInvoiceMemoLineTab";
    }
    
    
    
    /**
     * 
     * @description 获取采购订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectInvoiceLineModal")
    public String getSelectInvoiceLineModal(Pages pages, String poInvoiceHeadCode, ApInvoiceMemoLineCO payLineCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(1000);
        
        //分页查询采购发票行数据
        List<ApInvoiceLine> apInvoiceLineList = this.apInvoiceLineService.getApInvoiceLineListByHeadCode(poInvoiceHeadCode);
        
        //获取发票行数据
        List<ApInvoiceMemoLine> apInvoiceMemoLineList = this.apInvoiceMemoLineService.getApInvoiceMemoLineListByHeadCode(payLineCO.getInvoiceHeadCode());
        
        //剔除已经做了通知单行的发票行
        Iterator<ApInvoiceLine> apInvoiceLineIt = apInvoiceLineList.iterator();
        while(apInvoiceLineIt.hasNext()) {
            ApInvoiceLine apInvoiceLineTemp = apInvoiceLineIt.next();
            for(ApInvoiceMemoLine apInvoiceMemoLineTemp: apInvoiceMemoLineList) {
                if(apInvoiceLineTemp.getInvoiceLineCode().equals(apInvoiceMemoLineTemp.getInvoiceSourceLineCode())) {
                    apInvoiceLineIt.remove();
                    break;
                }
            }
        }
        //重置总数据数量
        pages.setDataNumber(apInvoiceLineList.size());
        
        //循环设置订单行相关信息
        for(ApInvoiceLine apInvoiceLineTemp: apInvoiceLineList) {
            PoLine poLine = this.poLineService.getDataObject(apInvoiceLineTemp.getInvoiceSourceLineCode());
            apInvoiceLineTemp.setMaterialCode(poLine.getMaterialCode());
            apInvoiceLineTemp.setPrice(poLine.getPrice());
            apInvoiceLineTemp.setUnit(poLine.getUnit());
        }
        
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //页面属性设置
        model.addAttribute("lineList", apInvoiceLineList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialMap", materialMap);
        model.addAttribute("materialUnitMap", materialUnitMap);
        
        return "apInvoiceMemo/pop/selectInvoiceLineModal";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-10-27 14:35:50
     * @author 
     * @param apInvoiceMemoLine
     * @param model
     * @return String
     *
     */
    @RequestMapping("getApInvoiceMemoLine")
    public String getApInvoiceMemoLine(ApInvoiceMemoLine apInvoiceMemoLine, String invoiceSourceType, Model model) {
        //查询要编辑的数据
        if(apInvoiceMemoLine!=null&&apInvoiceMemoLine.getInvoiceLineId()!=null) {
            apInvoiceMemoLine = this.apInvoiceMemoLineService.getDataObject(apInvoiceMemoLine.getInvoiceLineId());
            //根据来源获取单据数据
            if(StringUtils.isNotBlank(invoiceSourceType)) {
                //物料
                Map materialMap = this.masterDataCommonService.getMaterialMap();
                //物料单位
                Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
                
                //获取发票信息
                ApInvoiceLine apInvoiceLine = this.apInvoiceLineService.getDataObject(apInvoiceMemoLine.getInvoiceSourceLineCode());
                apInvoiceMemoLine.setInvoiceQuantity(apInvoiceLine.getQuantity());
                apInvoiceMemoLine.setPoLineAmount(apInvoiceLine.getAmount());
                //获取订单信息
                PoLine poLine = this.poLineService.getDataObject(apInvoiceLine.getInvoiceSourceLineCode());
                apInvoiceMemoLine.setMaterialCode(poLine.getMaterialCode());
                apInvoiceMemoLine.setMaterialName(materialMap.get(poLine.getMaterialCode()).toString());
                apInvoiceMemoLine.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(poLine.getMaterialCode()).getStandard());
                apInvoiceMemoLine.setPrice(poLine.getPrice());
                apInvoiceMemoLine.setUnit(materialUnitMap.get(poLine.getUnit()).toString());
            }
        }else {
            //根据来源获取单据数据
            /*
            if(StringUtils.isNotBlank(invoiceSourceType)) {
            }
            */
            
            apInvoiceMemoLine.setStandard(this.masterDataCommonService.getMdMaterialInfoCache(apInvoiceMemoLine.getMaterialCode()).getStandard());
        }
        
        //页面属性设置
        model.addAttribute("payLine", apInvoiceMemoLine);
        
        return "apInvoiceMemo/pop/addLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-10-27 14:35:50
     * @author 
     * @param apInvoiceMemoLine
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editApInvoiceMemoLine")
    @ResponseBody
    public String editApInvoiceMemoLine(@Valid ApInvoiceMemoLine apInvoiceMemoLine, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            /*
            //参数校验
            Map<String, String> errorMap = this.validateParameters(bindingResult, model);
            if(errorMap.size()>0) {
                return "forward:getPayLine";
            }
            */
            
            //对当前编辑的对象初始化默认的字段
            if(apInvoiceMemoLine.getInvoiceLineId()==null) {
                apInvoiceMemoLine.setInvoiceLineCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            this.apInvoiceMemoLineService.insertOrUpdateDataObject(apInvoiceMemoLine);
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-10-27 14:35:50
     * @author 
     * @param apInvoiceMemoLine
     * @return String
     *
     */
    @RequestMapping("deleteApInvoiceMemoLine")
    @ResponseBody
    public String deleteApInvoiceMemoLine(ApInvoiceMemoLine apInvoiceMemoLine, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(apInvoiceMemoLine!=null&&apInvoiceMemoLine.getInvoiceLineId()!=null) {
                //删除数据
                this.apInvoiceMemoLineService.deleteDataObject(apInvoiceMemoLine);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
}
